package com.zy.config.service.impl;

import com.zy.common.core.constant.CharacterCon;
import com.zy.common.core.constant.Constants;
import com.zy.config.dto.AppConfigDetailsDto;
import com.zy.config.dto.AppConfigQueryDto;
import com.zy.config.entity.AppConfig;
import com.zy.config.service.AppConfigDetailsService;
import com.zy.config.service.AppConfigService;
import com.zy.config.service.RemoteConfigProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @author 308237306_33141
 * @description:
 * @since 2023/3/18 19:31
 */
@Slf4j
@Service
public class RemoteConfigProviderImpl implements RemoteConfigProvider {

    @Value("${spring.application.name}")
    private String appName;

    @Resource
    private AppConfigService appConfigService;
    @Resource
    private AppConfigDetailsService appConfigDetailsService;

    @Override
    public Properties load(String appId) {
        try {
            String config = getStringProperties(appId);
            Properties properties = new Properties();
            properties.load(new StringReader(config));
            return properties;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return null;
    }

    @Override
    public String getStringProperties(String appId) {
        StringBuffer sb = new StringBuffer();
        getConfig(StringUtils.isBlank(appId) ? appName : appId).forEach(e -> sb.append(e.getAcdKey() + CharacterCon.COLON + e.getAcdValue() + "\n"));
        return sb.toString();
    }

    @Override
    public List<AppConfigDetailsDto> getListProperties(String appId) {
        return getConfig(StringUtils.isBlank(appId) ? appName : appId);
    }

    public List<AppConfigDetailsDto> getConfig(String appId) {
        List<AppConfig> configs = appConfigService.getConfigId(new AppConfigQueryDto(appId, Constants.DEV));
        if (CollectionUtils.isEmpty(configs)) {
            return null;
        }
        List<Long> configIds = configs.stream().map(e -> e.getId()).collect(Collectors.toList());
        return appConfigDetailsService.getDetails(configIds.get(0));

    }
}
